package cn.backflow.admin.service;

import cn.backflow.admin.dao.UserDao;
import cn.backflow.admin.entity.Department;
import cn.backflow.admin.common.Constants;
import cn.backflow.admin.dao.DepartmentDao;
import cn.backflow.admin.service.base.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class DepartmentService extends BaseService<Department, Integer> {

    private final DepartmentDao departmentDao;
    private final UserDao userDao;

    @Autowired
    public DepartmentService(DepartmentDao departmentDao, UserDao userDao) {
        this.departmentDao = departmentDao;
        this.userDao = userDao;
    }

    @Override
    public int save(Department entity) throws DataAccessException {
        prepareForSaveOrUpdate(entity);
        return super.update(entity);
    }

    @Override
    public int update(Department entity) throws DataAccessException {
        prepareForSaveOrUpdate(entity);
        return super.update(entity);
    }

    @Override
    public int saveOrUpdate(Department entity) throws DataAccessException {
        prepareForSaveOrUpdate(entity);
        return super.saveOrUpdate(entity);
    }

    @Override
    public int deleteById(Integer id) throws DataAccessException {
        userDao.separateDepartment(id);
        return super.deleteById(id);
    }

    /**
     * 设置部门层级与祖先路径
     */
    protected void prepareForSaveOrUpdate(Department department) {
        if (department.getId() == null)
            departmentDao.save(department);
        int level = 0;
        String ancestors = department.getId().toString();
        if (department.getParent() != null) {
            Department parent = getById(department.getParent());
            level = parent.getLevel() + 1;
            ancestors = parent.getAncestors() + "," + ancestors;
        }
        department.setLevel(level);
        department.setAncestors(ancestors);
    }

    public List<Department> findByUserId(Integer id) {
        return departmentDao.findByUserId(id);
    }

    public Map<Comparable, Department> findMap(Map<String, Object> filters) {
        return departmentDao.findMap(filters, "id");
    }
}